﻿using Koala.Framework;
using Koala.Framework.FileSystems.App_Data;
using Koala.Framework.Plugins;
using Koala.Framework.Plugins.Descriptors;
using Koala.Framework.Update;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows.Forms;

namespace Koala.JiraTool.PluginManager.Dialogs
{
    public partial class PluginUpdateDialog : Form, ITransientDependency
    {
        private readonly IPluginUpdateController _pluginUpdateController;
        private readonly IPluginManager _pluginManager;
        private readonly IAppDataFolder _appDataFolder;

        public PluginUpdateDialog(IPluginUpdateController pluginUpdateController, IPluginManager pluginManager, IAppDataFolder appDataFolder)
        {
            _pluginUpdateController = pluginUpdateController;
            _pluginManager = pluginManager;
            _appDataFolder = appDataFolder;
            InitializeComponent();
            DialogResult = DialogResult.Cancel;
        }

        private void tsbInstall_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.OK;
            var dictionary = new Dictionary<string, byte[]>();
            foreach (DataGridViewRow row in dgvMain.SelectedRows)
            {
                var name = row.Cells["SymbolicName"].Value.ToString();
                var bytes = _pluginUpdateController.GetPluginInstallPackage(name);
                dictionary.Add(name, bytes);
            }

            if (!_appDataFolder.DirectoryExists("Temp"))
                _appDataFolder.CreateDirectory("Temp");
            var isError = false;
            foreach (var item in dictionary)
            {
                var filePath = _appDataFolder.MapPath(Path.Combine("Temp", Guid.NewGuid() + ".zip"));
                var file = new FileInfo(filePath);
                try
                {
                    var name = item.Key;
                    var value = item.Value;
                    using (var write = file.Create())
                    {
                        write.Write(value, 0, value.Length);
                    }
                    if (!_pluginManager.Uninstall(name))
                    {
                        isError = true;
                    }
                    if (!_pluginManager.Instanll(new PluginInstanllDescriptor
                    {
                        PackagePath = filePath
                    }))
                    {
                        isError = true;
                    }
                }
                finally
                {
                    if (file.Exists)
                        file.Delete();
                }
            }
            MessageBox.Show(isError ? "安装过程中发现了一些错误，一些插件可能没有被正常安装，查看详细错误请查看日志文件：AppData\\Logs。" : "安装成功，可能会有一些功能在重启应用程序之后才会生效。");

            Close();
        }

        private void PluginUpdateDialog_Load(object sender, EventArgs e)
        {
            dgvMain.DataSource = null;
            var list = _pluginUpdateController.GetCanUpdatePluginDescriptors();
            if (list == null || !list.Any())
            {
                Text = "当前插件都是最新的";
                return;
            }
            dgvMain.DataSource = list;
        }
    }
}